const mongoose = require('mongoose');
require('dotenv').config();

// 导入模型
const User = require('../src/models/user.model');
const Shop = require('../src/models/shop.model');
const Product = require('../src/models/product.model');

async function quickSetup() {
  try {
    console.log('🔗 连接到数据库...');
    await mongoose.connect(process.env.MONGODB_URI);
    console.log('✅ 数据库连接成功');

    // 1. 创建测试用户
    console.log('👤 创建测试用户...');
    let testUser = await User.findOne({ email: 'test@example.com' });
    if (!testUser) {
      testUser = await User.create({
        name: '测试用户',
        email: 'test@example.com',
        password: '$2a$10$rOvHmj1qGZpKZOKJQKQKQeX8QKQKQeX8QKQKQeX8QKQKQeX8QKQKQ', // 密码: 123456
        phone: '13800138000',
        isVerified: true
      });
      console.log('✅ 用户创建成功:', testUser.name);
    } else {
      console.log('✅ 用户已存在:', testUser.name);
    }

    // 2. 创建测试店铺
    console.log('🏪 创建测试店铺...');
    const testShop = await Shop.create({
      name: 'Apple官方旗舰店',
      description: 'Apple官方授权旗舰店，正品保证，全国联保',
      logo: 'https://via.placeholder.com/200x200/007AFF/fff?text=Apple',
      banner: 'https://via.placeholder.com/800x300/007AFF/fff?text=Apple+Store',
      owner: testUser._id,
      type: 'official',
      status: 'active',
      categories: ['手机数码', '电脑办公'],
      rating: {
        overall: 4.9,
        service: 4.9,
        logistics: 4.8,
        description: 4.9
      },
      certification: {
        isVerified: true,
        verifiedAt: new Date(),
        businessLicense: 'BL001'
      },
      shipping: {
        freeShippingThreshold: 0,
        shippingFee: 0,
        supportedRegions: ['全国'],
        averageDeliveryTime: 1
      },
      afterSales: {
        returnPolicy: '15天无理由退货',
        warrantyPeriod: 365,
        supportRefund: true,
        supportExchange: true
      },
      stats: {
        totalProducts: 0,
        totalSales: 10000,
        totalOrders: 5000,
        monthlyRevenue: 500000,
        followers: 50000
      }
    });
    console.log('✅ 店铺创建成功:', testShop.name);

    // 3. 创建测试商品
    console.log('📦 创建测试商品...');
    const products = [
      {
        name: 'iPhone 15 Pro Max 256GB 深空黑色',
        description: 'iPhone 15 Pro Max 采用钛金属设计，配备 A17 Pro 芯片，支持 5G 网络，拥有专业级摄像系统。',
        price: 9999,
        originalPrice: 10999,
        mainImage: 'https://via.placeholder.com/400x400/333/fff?text=iPhone+15+Pro+Max',
        images: [
          'https://via.placeholder.com/400x400/333/fff?text=iPhone+15+Pro+Max',
          'https://via.placeholder.com/400x400/666/fff?text=侧面图',
          'https://via.placeholder.com/400x400/999/fff?text=背面图'
        ],
        category: 'electronics',
        brand: 'Apple',
        shop: testShop._id,
        stock: 50,
        sales: 1000,
        isFeatured: true,
        isActive: true,
        tags: ['自营', '免息', '顺丰配送'],
        specs: {
          '颜色': ['深空黑色', '自然钛金色', '蓝色钛金色', '白色钛金色'],
          '容量': ['256GB', '512GB', '1TB']
        },
        features: [
          '6.7英寸超视网膜XDR显示屏',
          'A17 Pro芯片，6核CPU',
          '专业级摄像系统',
          '钛金属设计',
          '支持5G网络'
        ]
      },
      {
        name: '小米14 Ultra 16GB+512GB 黑色',
        description: '小米14 Ultra 搭载骁龙8 Gen3处理器，徕卡专业摄影，120W极速充电。',
        price: 6999,
        originalPrice: 7999,
        mainImage: 'https://via.placeholder.com/400x400/ff6900/fff?text=Xiaomi+14+Ultra',
        images: [
          'https://via.placeholder.com/400x400/ff6900/fff?text=Xiaomi+14+Ultra',
          'https://via.placeholder.com/400x400/333/fff?text=侧面图',
          'https://via.placeholder.com/400x400/666/fff?text=背面图'
        ],
        category: 'electronics',
        brand: 'Xiaomi',
        shop: testShop._id,
        stock: 30,
        sales: 500,
        isFeatured: true,
        isActive: true,
        tags: ['特惠', '包邮'],
        specs: {
          '颜色': ['黑色', '白色', '蓝色'],
          '内存': ['16GB+512GB', '16GB+1TB']
        },
        features: [
          '6.73英寸2K曲面屏',
          '骁龙8 Gen3处理器',
          '徕卡专业摄影',
          '120W极速充电',
          '5300mAh大电池'
        ]
      },
      {
        name: 'MacBook Pro 14英寸 M3芯片',
        description: 'MacBook Pro 14英寸搭载M3芯片，专业级性能，适合创意工作者。',
        price: 14999,
        originalPrice: 16999,
        mainImage: 'https://via.placeholder.com/400x400/007AFF/fff?text=MacBook+Pro+14',
        images: [
          'https://via.placeholder.com/400x400/007AFF/fff?text=MacBook+Pro+14',
          'https://via.placeholder.com/400x400/333/fff?text=侧面图',
          'https://via.placeholder.com/400x400/666/fff?text=键盘图'
        ],
        category: 'electronics',
        brand: 'Apple',
        shop: testShop._id,
        stock: 20,
        sales: 200,
        isFeatured: true,
        isActive: true,
        tags: ['自营', '分期'],
        specs: {
          '颜色': ['深空灰色', '银色'],
          '配置': ['M3 8核CPU', 'M3 Pro 11核CPU', 'M3 Max 14核CPU']
        },
        features: [
          '14.2英寸Liquid Retina XDR显示屏',
          'M3芯片，8核CPU',
          '最长22小时电池续航',
          '1080p FaceTime高清摄像头',
          '六扬声器音响系统'
        ]
      },
      {
        name: '华为Mate60 Pro 12GB+256GB',
        description: '华为Mate60 Pro 搭载麒麟9000S芯片，支持卫星通话，专业摄影系统。',
        price: 6999,
        originalPrice: 7999,
        mainImage: 'https://via.placeholder.com/400x400/FF3B30/fff?text=Huawei+Mate60+Pro',
        images: [
          'https://via.placeholder.com/400x400/FF3B30/fff?text=Huawei+Mate60+Pro',
          'https://via.placeholder.com/400x400/333/fff?text=侧面图',
          'https://via.placeholder.com/400x400/666/fff?text=背面图'
        ],
        category: 'electronics',
        brand: 'Huawei',
        shop: testShop._id,
        stock: 40,
        sales: 800,
        isFeatured: true,
        isActive: true,
        tags: ['热销', '包邮'],
        specs: {
          '颜色': ['雅川青', '白沙银', '雅丹黑', '南糯紫'],
          '内存': ['12GB+256GB', '12GB+512GB', '12GB+1TB']
        },
        features: [
          '6.82英寸OLED曲面屏',
          '麒麟9000S芯片',
          '支持卫星通话',
          '5000万像素超光变摄像头',
          '5000mAh电池'
        ]
      }
    ];

    const createdProducts = await Product.insertMany(products);
    console.log(`✅ 创建了 ${createdProducts.length} 个商品`);

    // 4. 更新店铺统计
    await Shop.findByIdAndUpdate(testShop._id, {
      'stats.totalProducts': createdProducts.length
    });
    console.log('✅ 店铺统计更新完成');

    console.log('\n🎉 快速设置完成！');
    console.log('📊 数据统计:');
    console.log(`- 用户: 1`);
    console.log(`- 店铺: 1`);
    console.log(`- 商品: ${createdProducts.length}`);

    console.log('\n🔗 可用的商品ID:');
    createdProducts.forEach((product, index) => {
      console.log(`${index + 1}. ${product.name}: ${product._id}`);
    });

  } catch (error) {
    console.error('❌ 设置失败:', error);
  } finally {
    await mongoose.disconnect();
    console.log('👋 数据库连接已关闭');
  }
}

quickSetup();
